package com.pearl.common.spring;

import com.pearl.common.entity.User;

/**
 * Bean对象工具类
 *
 * @author yyb
 * @create 2020/5/6
 */
public class BeanUtils {
    /**
     * 匹配getter方法的前缀
     */
    private static final String GET_PREFIX = "get";

    /**
     * 匹配setter方法的前缀
     */
    private static final String SET_PREFIX = "set";

    /**
     * 根据对象和字段名称获取get方法返回值
     *
     * @param t    对象
     * @param name 字段名称
     * @param <T>
     * @return
     */
    public static <T> String getMethodValue(T t, String name) {
        String methodName = GET_PREFIX + name.substring(0, 1).toUpperCase() + name.substring(1);
        String value = "";
        try {
            value = String.valueOf(t.getClass().getMethod(methodName).invoke(t));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    public static void main(String[] args) {
        //根据对象和字段名称获取get方法返回值
        User user = new User("1", "张三", 18);
        String nameVale = getMethodValue(user, "name");
        System.out.printf("name：" + nameVale);

    }

}
